package com.sztle.admodule.handler;

import android.app.Activity;
import android.text.TextUtils;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationAdEcpmInfo;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationBaseManager;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationFullScreenManager;
import com.sztle.admodule.GmAdManager;
import com.sztle.admodule.IShowListener;
import com.sztle.admodule.bean.AdConfigInfo;
import com.sztle.admodule.bean.RequestAdEntity;
import com.sztle.admodule.outstatus.AppStatusProcessor;
import com.sztle.admodule.control.manager.ControlManager;
import com.sztle.admodule.myutils.AdLogUtils;

public class FullIntlHandler {
    //全屏插屏广告
    private static final String TAG = "FullIntlHandler";
    private static TTFullScreenVideoAd useShowFullScreenVideoAd;
    private static TTFullScreenVideoAd lastUseShowFullScreenVideoAd;
    private static boolean isLoading = false;
    private static boolean isShowing = false;
    private static TTFullScreenVideoAd hasShowFullScreenVideoAd;
    private static long lastShowTime = 0;

    /**
     * @param position 0,1,2 插屏1 插屏2 插屏3
     * @return
     */
    private static String getCode(int position) {
        if (position == 0) {
            AdLogUtils.Log(TAG,"加载插屏1");
            AdConfigInfo adConfigInfo = ControlManager.getAdConfigInfo();
            if (adConfigInfo != null && !TextUtils.isEmpty(adConfigInfo.int1Id.trim())) {
                return adConfigInfo.int1Id;
            }
            return AppStatusProcessor.getAppParam().interstitialAdId;
        } else if (position == 1) {
            AdLogUtils.Log(TAG,"加载插屏2");
            AdConfigInfo adConfigInfo = ControlManager.getAdConfigInfo();
            if (adConfigInfo != null && !TextUtils.isEmpty(adConfigInfo.int2Id.trim())) {
                return adConfigInfo.int2Id;
            }
            return AppStatusProcessor.getAppParam().interstitialAdId;
        } else {
            AdLogUtils.Log(TAG,"加载插屏3");
            AdConfigInfo adConfigInfo = ControlManager.getAdConfigInfo();
            if (adConfigInfo != null && !TextUtils.isEmpty(adConfigInfo.int3Id.trim())) {
                return adConfigInfo.int3Id;
            }
            return AppStatusProcessor.getAppParam().interstitialAdId;
        }
    }

    public static boolean canLoad() {
        if (!GmAdManager.isUseAdExp()) {
            return false;
        }
        if (!GmAdManager.isAdSdkReady()) {
            return false;
        }
        if (isLoading) {
            return false;
        }
        if (isShowing) {
            return false;
        }
        return true;
    }

    /**
     * @param position     0,1,2 插屏1 插屏2 插屏3
     * @param activity
     * @param showListener
     */
    public static void loadAndShow(int position, Activity activity, IShowListener showListener) {
        if (activity == null) {
            if (showListener != null) {
                showListener.onJustEnd(false);
            }
            return;
        }
        if (!canLoad()) {
            if (showListener != null) {
                showListener.onJustEnd(false);
            }
            return;
        }
        if (isReady()) {
            show(activity, showListener);
            return;
        }
        /** 1、创建AdSlot对象 */
        String codeId = getCode(position);
        AdLogUtils.Log(TAG,"加载插屏ID："+codeId);
        AdSlot adslot = new AdSlot.Builder()
                .setCodeId(codeId)
                .setOrientation(TTAdConstant.ORIENTATION_VERTICAL)
                .setMediationAdSlot(new MediationAdSlot.Builder()
                        .setMuted(true)//是否静音
                        .setVolume(0.1f)//设置音量
                        .setBidNotify(true)//竞价结果通知
                        .build())
                .build();

        /** 2、创建TTAdNative对象 */

        TTAdNative adNativeLoader = GmAdManager.get().createAdNative(activity);

        /** 3、加载广告 */
        isLoading = true;
        GmAdManager.enterRequestAdQueue(new RequestAdEntity(RequestAdEntity.TYPE_AD_INT));
        adNativeLoader.loadFullScreenVideoAd(adslot, new TTAdNative.FullScreenVideoAdListener() {
            @Override
            public void onError(int i, String s) {
                isLoading = false;
                AdLogUtils.Log(TAG, "onError = " + s);
                if (showListener != null) {
                    showListener.onAdLoadEnd(false);
                }
            }

            @Override
            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ttFullScreenVideoAd) {
                if (showListener != null) {
                    showListener.onAdLoadEnd(true);
                }
                AdLogUtils.Log(TAG, "onFullScreenVideoLoaded");
            }

            @Override
            public void onFullScreenVideoCached() {
                AdLogUtils.Log(TAG, "onFullScreenVideoCached");
            }

            @Override
            public void onFullScreenVideoCached(TTFullScreenVideoAd ttFullScreenVideoAd) {
                AdLogUtils.Log(TAG, "onFullScreenVideoCached");
                isLoading = false;
                //建议该回调后进行广告展示
                closeAd();
                useShowFullScreenVideoAd = ttFullScreenVideoAd;
                show(activity, showListener);
            }
        });
    }


    public static void closeAd() {
//        if (System.currentTimeMillis() - lastShowTime < 1000) {
//            ThreadUtils.runOnUiThreadDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    destroyOldAd();
//                }
//            }, 1000);
//            return;
//        }
        destroyOldAd();
    }


    private static void destroyOldAd() {
        if (hasShowFullScreenVideoAd != null) {
            MediationFullScreenManager screenManager = hasShowFullScreenVideoAd.getMediationManager();
            if (screenManager != null) {
                screenManager.destroy();
            }
            hasShowFullScreenVideoAd = null;
        }
    }


    //可以先预加载
    public static void preLoad(int position,Activity activity, IShowListener showListener) {
        if (activity == null) {
            if (showListener != null) {
                showListener.onJustEnd(false);
            }
            return;
        }
        if(!canLoad()){
            if(showListener != null){
                showListener.onAdLoadEnd(false);
            }
            return;
        }
        if (isReady()) {
            if (showListener != null) {
                showListener.onAdLoadEnd(true);
            }
            return;
        }


        /** 1、创建AdSlot对象 */
        AdSlot adslot = new AdSlot.Builder()
                .setCodeId(getCode(position))
                .setOrientation(TTAdConstant.ORIENTATION_VERTICAL)
                .setMediationAdSlot(new MediationAdSlot.Builder()
                        .setMuted(true)//是否静音
                        .setVolume(0.1f)//设置音量
                        .setBidNotify(true)//竞价结果通知
                        .build())
                .build();

        /** 2、创建TTAdNative对象 */

        TTAdNative adNativeLoader = GmAdManager.get().createAdNative(activity);
        GmAdManager.enterRequestAdQueue(new RequestAdEntity(RequestAdEntity.TYPE_AD_INT));
        /** 3、加载广告 */
        isLoading = true;
        adNativeLoader.loadFullScreenVideoAd(adslot, new TTAdNative.FullScreenVideoAdListener() {
            @Override
            public void onError(int i, String s) {
                AdLogUtils.Log(TAG, "onError = " + s);
                if (showListener != null) {
                    showListener.onAdLoadEnd(false);
                }
                isLoading = false;
            }

            @Override
            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ttFullScreenVideoAd) {
                AdLogUtils.Log(TAG, "onFullScreenVideoLoaded");
                if (showListener != null) {
                    showListener.onAdLoadEnd(true);
                }
                useShowFullScreenVideoAd = ttFullScreenVideoAd;
            }

            @Override
            public void onFullScreenVideoCached() {
                AdLogUtils.Log(TAG, "onFullScreenVideoCached");
            }

            @Override
            public void onFullScreenVideoCached(TTFullScreenVideoAd ttFullScreenVideoAd) {
                AdLogUtils.Log(TAG, "onFullScreenVideoCached");
                //建议该回调后进行广告展示
                isLoading = false;
                useShowFullScreenVideoAd = ttFullScreenVideoAd;
            }
        });
    }


    public static boolean isReady() {
        return useShowFullScreenVideoAd != null
                && useShowFullScreenVideoAd.getMediationManager() != null
                && useShowFullScreenVideoAd.getMediationManager().isReady();
    }


    public static void show(Activity activity, IShowListener showListener) {
        if (!GmAdManager.isUseAdExp()) {
            if (showListener != null) {
                showListener.onJustEnd(false);
            }
            return;
        }
        if (activity == null) {
            if (showListener != null) {
                showListener.onJustEnd(false);
            }
            AdLogUtils.Log(TAG, "FullScreenVideoAd is null");
            return;
        }
        if (!isReady()) {
            if (showListener != null) {
                showListener.onJustEnd(false);
            }
            AdLogUtils.Log(TAG, "ad not ready");
            return;
        }

        isShowing = true;
        useShowFullScreenVideoAd.setFullScreenVideoAdInteractionListener(new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {
            @Override
            public void onAdShow() {
                AdLogUtils.Log(TAG, "onAdShow");
                isShowing = true;
                lastShowTime = System.currentTimeMillis();
                hasShowFullScreenVideoAd = useShowFullScreenVideoAd;
                if (showListener != null) {
                    showListener.onAdShow(getEcpm());
                }
            }

            @Override
            public void onAdVideoBarClick() {
                AdLogUtils.Log(TAG, "onAdVideoBarClick");
            }

            @Override
            public void onAdClose() {
                AdLogUtils.Log(TAG, "onAdClose");
                if (showListener != null) {
                    showListener.onJustEnd(true);
                }
                isShowing = false;
            }

            @Override
            public void onVideoComplete() {
                AdLogUtils.Log(TAG, "onVideoComplete");
            }

            @Override
            public void onSkippedVideo() {
                AdLogUtils.Log(TAG, "onSkippedVideo");
                isShowing = false;
            }
        });

        useShowFullScreenVideoAd.showFullScreenVideoAd(activity);

    }

    private static String getEcpm() {
        if (useShowFullScreenVideoAd == null) {
            return "";
        }
        MediationBaseManager mediationManager = useShowFullScreenVideoAd.getMediationManager();
        if (mediationManager != null) {
            MediationAdEcpmInfo showEcpm = mediationManager.getShowEcpm();
            return showEcpm.getEcpm();
        }
        return "";
    }

    private static void showEcpmInfo() {
        if (useShowFullScreenVideoAd == null) {
            return;
        }
        MediationBaseManager mediationManager = useShowFullScreenVideoAd.getMediationManager();
        if (mediationManager != null) {
            MediationAdEcpmInfo showEcpm = mediationManager.getShowEcpm();
            if (showEcpm != null) {
                logEcpmInfo(showEcpm);
            }
        }
    }

    private static void logEcpmInfo(MediationAdEcpmInfo item) {
        AdLogUtils.Log(TAG, "EcpmInfo: \n" +
                "SdkName: " + item.getSdkName() + ",\n" +
                "CustomSdkName: " + item.getCustomSdkName() + ",\n" +
                "SlotId: " + item.getSlotId() + ",\n" +
                // 单位：分
                "Ecpm: " + item.getEcpm() + ",\n" +
                "ReqBiddingType: " + item.getReqBiddingType() + ",\n" +
                "ErrorMsg: " + item.getErrorMsg() + ",\n" +
                "RequestId: " + item.getRequestId() + ",\n" +
                "RitType: " + item.getRitType() + ",\n" +
                "AbTestId: " + item.getAbTestId() + ",\n" +
                "ScenarioId: " + item.getScenarioId() + ",\n" +
                "SegmentId: " + item.getSegmentId() + ",\n" +
                "Channel: " + item.getChannel() + ",\n" +
                "SubChannel: " + item.getSubChannel() + ",\n" +
                "customData: " + item.getCustomData()
        );
    }

    public static void setClearFlag(){
        isShowing = false;
        isLoading = false;
    }
}
